<template>
  <el-popover
    placement="bottom"
    trigger="click"
    v-model:visible="visible"
    :width="popWidth"
    :popper-class="$style['pop-container']"
  >
    <template #reference>
      <el-input
        v-bind="$attrs"
        @focus="focus"
        v-model="inputData"
        size="small"
        :value="inputValue"
        readonly
      ></el-input>
    </template>
    <el-tree
      :data="treeData"
      v-bind="treeProps"
      :expand-on-click-node="false"
      @node-click="nodeClick"
      :default-expanded-keys="expandedKeys"
      highlight-current
      accordion
      ref="treeRef"
      default-expand-all
    ></el-tree>
  </el-popover>
</template>

<script lang="ts">
import { Emit, Model, Prop, Ref, Vue } from 'vue-property-decorator'
import { ObjectType } from 'typings/interfaces'
import { requestOrgTree2 } from '@/api/global'

export default class SelectTree extends Vue {
  @Model('modelValue', { type: String, default: '' }) public value!: string
  // @Prop({ type: Array, default: () => [] }) treeData!: any[]
  @Prop({ type: Object, default: () => ({}) }) treeProps!: any
  @Ref() readonly treeRef!: any
  @Emit()
  selectChange(data) {
    return data
  }
  treeData = []
  visible = false
  popWidth = 150
  inputData = ''
  expandedKeys: Array<string> = []

  get inputValue() {
    if (!this.value) return ''
    const label = this?.treeProps?.props?.label || 'label'
    const key = this?.treeProps?.nodeKey || this?.treeProps['node-key'] || 'key'
    const stack: Array<string> = []
    this.treeRef && this.treeRef.setCurrentKey(this.value)
    const rst = treeRecursion(this.treeData, this.value) || ''
    this.expandedKeys = stack
    this.inputData = rst
    return rst

    function treeRecursion(data: ObjectType[], val: string): string | undefined {
      for (let i = 0, l = data.length; i < l; i++) {
        const item = data[i]
        if (item[key] === val) return item[label]
        if (item.children && item.children.length > 0) {
          stack.push(item[key])
          const rst = treeRecursion(item.children, val)
          if (rst) return rst
        }
      }
      stack.pop()
      return
    }
  }
  async mounted() {
    const rst = await requestOrgTree2()
    this.treeData = rst.data.data
  }

  nodeClick(data: any) {
    this.visible = false
    this.value = data.id
    this.selectChange(data)
  }

  focus(e: any) {
    this.popWidth = e.target.offsetWidth
  }
}
</script>

<style module lang="scss">
.pop-container {
  box-sizing: border-box;
  max-height: 400px;
  overflow: auto;

  :global {
    .el-tree-node__children {
      overflow: inherit !important;
    }
  }
}
</style>
